package com.ruoyi.system.controller;

import com.dyun.tool.ssecurity.utils.YunSecurityUtils;
import com.ruoyi.project.setting.security.LoginUser;
import com.ruoyi.project.setting.security.service.SysLoginService;
import com.ruoyi.project.setting.security.service.TokenService;
import com.ruoyi.common.annotation.SysLog;
import com.ruoyi.common.enums.BusinessTypeEnum;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.project.system.entity.SysRole;
import com.ruoyi.project.system.entity.SysUser;
import com.ruoyi.project.system.service.ISysDeptService;
import com.ruoyi.project.system.service.ISysUserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.core.result.R;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 个人中心
 *
 * @author dyun
 */
@Slf4j
@RestController
@RequestMapping("/system/user/profile")
@AllArgsConstructor
public class SysProfileController extends BaseController {
    private final SysLoginService loginService;

    private final TokenService tokenService;

    private final ISysUserService sysUserService;

    private final ISysDeptService sysDeptService;

    /**
     * 查看个人信息
     */
    @GetMapping
    public R profile() {
        LoginUser loginUser = tokenService.currentLoginUser();
        SysUser user = loginUser.getSysUser();
        Map<String, Object> ajax = new HashMap<>(16);
        ajax.put("user", user);
        ajax.put("deptName", sysDeptService.getById(user.getCreateDept()).getDeptName());
        ajax.put("roleGroup", loginUser.getRoleList().stream().map(SysRole::getRoleName).collect(Collectors.joining()));
        return success(ajax);
    }

    /**
     * 修改个人信息
     */
    @SysLog(title = "个人信息", businessType = BusinessTypeEnum.UPDATE)
    @PutMapping
    public R updateProfile(@Validated @RequestBody SysUser sysUser) {
        SysUser user;
        try {
            LoginUser loginUserOld = tokenService.currentLoginUser();
            SysUser oldUser = loginUserOld.getSysUser();
            user = new SysUser();
            user.setId(oldUser.getId());
            // 只允许修改这几项信息
            user.setAvatar(sysUser.getAvatar());
            user.setNickName(sysUser.getNickName());
            user.setPhone(sysUser.getPhone());
            user.setEmail(sysUser.getEmail());
            user.setSex(sysUser.getSex());
            sysUserService.updateById(user);

            loginService.initLoginUser(loginUserOld.getToken(), oldUser);
        } catch (Exception e) {
            log.error(e.getMessage());
            return fail("修改个人信息异常，请联系管理员");
        }
        return success();
    }

    /**
     * 重置密码
     */
    @SysLog(title = "个人信息", businessType = BusinessTypeEnum.UPDATE)
    @PutMapping("/updatePwd")
    public R updatePwd(String oldPassword, String newPassword) {
        LoginUser loginUser = tokenService.currentLoginUser();
        SysUser oldUser = loginUser.getSysUser();
        String password = oldUser.getPassword();
        PasswordEncoder passwordEncoder = YunSecurityUtils.getPasswordEncoder();
        if (!Objects.requireNonNull(passwordEncoder).matches(oldPassword, password)) {
            return fail("修改密码失败，旧密码错误");
        }
        if (passwordEncoder.matches(newPassword, password)) {
            return fail("新密码不能与旧密码相同");
        }
        SysUser user = new SysUser();
        user.setId(oldUser.getId());
        user.setPassword(passwordEncoder.encode(newPassword));

        return status(sysUserService.updateById(user), "修改密码异常，请联系管理员");
    }
}
